package com.larissa.android.quizdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity{
    private static final String TAG="MainActivity";
    private QuizViewModel mQuizViewModel;
    private TextView mQuestionTextView;
    private Button mTrueButton;
    private Button mFalseButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG,"onCreate() called");
        mQuizViewModel=new ViewModelProvider(this).get(QuizViewModel.class);
        Log.d(TAG,String.format("Got a QuizViewModel:%s",mQuizViewModel));

        mQuestionTextView=(TextView) findViewById(R.id.tx_question);
        mTrueButton=(Button) findViewById(R.id.btn_true);
        mFalseButton=(Button) findViewById(R.id.btn_false);

        mTrueButton.setOnClickListener(view -> {
            if(mQuizViewModel.isCurrentQuestionAnswer())
                mQuizViewModel.mCount++;
            updateQuestion();
        });
        mFalseButton.setOnClickListener(view -> {
            if(!mQuizViewModel.isCurrentQuestionAnswer())
                mQuizViewModel.mCount++;
            updateQuestion();
        });

        showQuestion();
    }

    private void updateQuestion(){
        mQuizViewModel.moveToNext();
        showQuestion();
    }

    private void showQuestion(){
        int mCurrentIdx=mQuizViewModel.mCurrentIdx;
        int mQuestionId=mQuizViewModel.getCurrentQuestionText();
        if(mCurrentIdx==-1){
            mTrueButton.setEnabled(false);
            mFalseButton.setEnabled(false);
            String toastText=String.format("%s questions are right.",mQuizViewModel.mCount);
            Toast.makeText(MainActivity.this,toastText,Toast.LENGTH_SHORT).show();
            mQuestionTextView.setText(mQuestionId);
        }
        else{
            mQuestionTextView.setText(mQuestionId);
        }
    }

    @Override
    public void onStart(){
        super.onStart();
        Log.d(TAG,"onStart() called");
    }

    @Override
    public void onResume(){
        super.onResume();
        Log.d(TAG,"onResume() called");
    }

    @Override
    public void onPause(){
        super.onPause();
        Log.d(TAG,"onPause() called");
    }

    @Override
    public void onStop(){
        super.onStop();
        Log.d(TAG,"onStop() called");
    }
    @Override
    public void onDestroy(){
        super.onDestroy();
        Log.d(TAG,"onDestroy() called");
    }
}